/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.cmd.entity;

import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.entities.beans.project.ProjectBean;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.vos.EntityVo;
import cn.easyplatform.type.EntityType;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class QueryTableCmd implements Command<List<EntityVo>> {

	private String dbId;

	public QueryTableCmd(String dbId) {
		this.dbId = dbId;
	}

	@Override
	public List<EntityVo> execute(CommandContext cc) {
		ProjectBean pb = cc.getProject();
		if (pb.getBizDb().equals(dbId))
			dbId = "";
		StringBuilder sb = new StringBuilder("select entityId,name,desp from ");
		sb.append(pb.getEntityTableName()).append(" where type='")
				.append(EntityType.TABLE.getName()).append("' AND ");
		if (Strings.isBlank(dbId))
			sb.append("(subType='' OR subType IS NULL OR subType='")
					.append(pb.getBizDb()).append("')");
		else
			sb.append("subType='").append(dbId).append("'");
		sb.append(" ORDER BY entityId");
		List<BaseEntity> data = cc.getEntityDao().selectEntity(sb.toString(),
				null);
		List<EntityVo> result = new ArrayList<EntityVo>();
		for (BaseEntity ev : data)
			result.add(new EntityVo(ev.getId(), ev.getName(), ev
					.getDescription(), EntityType.TABLE.getName(), dbId));
		data = null;
		return result;
	}
}
